package com.newhonor.server.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.newhonor.server.mapper.MailLogMapper;
import com.newhonor.server.pojo.*;
import com.newhonor.server.service.IEmployeeService;
import com.newhonor.server.service.IJoblevelService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Author newhonor
 * @Date 2021/2/23 22:12
 * @Version 1.0
 **/
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;

    @ApiOperation("获取所有员工(分页)")
    @GetMapping("/")
    public RespPageBean getEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    Employee employee,
                                    LocalDate[] beginDateScope) {

        return employeeService.getEmployeeByPage(currentPage, size, employee, beginDateScope);
    }

    @ApiOperation("导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        List<Employee> employees = employeeService.getEmployee(null);
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employees);
        ServletOutputStream outputStream = null;

        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream)
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public ResBean importEmployee(MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Joblevel> joblevels = joblevelService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(),Employee.class,params);
            list.forEach(employee -> {
                //设置id方法2
//                employee.setJoblevelId(joblevels.get(joblevels.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                for (Joblevel joblevel : joblevels) {
                    if(joblevel.getName().equals(employee.getJoblevel().getName())){
                        employee.setJoblevelId(joblevel.getId());
                        break;
                    }
                }
            });
            System.out.println(list);
            if(employeeService.saveBatch(list)){
                return ResBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResBean.error("导入失败");
    }

    @GetMapping("/mail")
    public ResBean mailSend(){
        Employee employee = employeeService.getEmployee(1).get(0);
        /**
         * 消息入库
         *
         */

        //测试3，消费端只消费一次
//        String msgId = "123";
        String msgId = UUID.randomUUID().toString();
        MailLog mailLog = new MailLog();
        mailLog.setMsgId(msgId);
        mailLog.setEid(employee.getId());
        mailLog.setStatus(0);
        mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
        mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
        mailLog.setCount(0);
        mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
        mailLog.setCreateTime(LocalDateTime.now());
        mailLog.setUpdateTime(LocalDateTime.now());
        mailLogMapper.insert(mailLog);

        //employee pojo必须实现序列化
        //失败测试1，重试发送成功
//        rabbitTemplate.convertAndSend("MailConstants.MAIL_EXCHANGE_NAME",MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(msgId));
        rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(msgId));
        return ResBean.success("发送成功",employee);

    }


    //工号(String -> Integer)转换
//    public ResBean maxWorkID(){
//        List<Map<String,Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
//        return ResBean.success(null, String.format("%008d",Integer.parseInt(maps.get(0).get("max(workID)").toString())+1));
//    }

    //处理时间
//    public ResBean addEmp(Employee employee){
//        LocalDate beginContract = employee.getBeginDate();
//        LocalDate endContract = employee.getEndDate();
//        long days = beginContract.until(endContract, ChronoUnit.DAYS);
//        DecimalFormat decimalFormat = new DecimalFormat("##.00");
//        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
//    }


}
